const Tags = require('../../models/good/tag');
class TagService {
    static async getTagList({ pageNum = 1, pageSize = 10 }, data) {
        try {
            // 参数类型转换和验证
            const pageNumInt = parseInt(pageNum) || 1;
            const pageSizeInt = parseInt(pageSize) || 10;
            
            // 限制pageSize最大值，防止恶意请求
            const limit = Math.min(pageSizeInt, 100);
            const skip = (pageNumInt - 1) * limit;
            
            // 构建查询条件
            const query = {};
            if (data?.name) {
                query.name = { $regex: data.name, $options: 'i' };
            }
            if (data?.disable !== undefined) {
                query.disable = data.disable;
            }
            if (data?.type) {
                query.type = data.type;
            }
            if (data?.createTime) {
                query.createTime = { $gte: new Date(data.createTime) };
            }
            
            const total = await Tags.countDocuments(query);
            const tagList = await Tags.find(query).skip(skip).limit(limit).lean();
                
            return {
                total,
                page: pageNumInt,
                totalPages: Math.ceil(total / limit),
                list: tagList
            };
        } catch (error) {
            throw new Error(`获取标签列表失败: ${error.message}`);
        }
    }
    static async getTagTypeList() {
        let res=await Tags.distinct('type');
        console.log(res);
        return await Tags.distinct('type');
    }
    static async getTagById(tagId) {
        return await Tags.findById(tagId).lean();
    }
    static async createTag(data) {
        try {
            // 验证必要字段
            if (!data || !data.name || !data.type) {
                throw new Error('标签名称和类型为必填项');
            }
            
            // 设置创建时间
            data.createTime = Date.now();
            
            return await Tags.create(data);
        } catch (error) {
            throw new Error(`创建标签失败: ${error.message}`);
        }
    }

    static async updateTag(data) {
        try {
            // 验证必要字段
            if (!data || !data.id) {
                throw new Error('标签ID为必填项');
            }
            
            const { id, ...updateData } = data;
            
            // 移除不应被更新的字段
            delete updateData._id;
            delete updateData.createTime;
            
            return await Tags.findByIdAndUpdate(id, updateData, { new: true });
        } catch (error) {
            throw new Error(`更新标签失败: ${error.message}`);
        }
    }
    static async deleteTag(tagId) {
        try {
            // 验证必要参数
            if (!tagId) {
                throw new Error('标签ID为必填项');
            }
            
            return await Tags.findByIdAndDelete(tagId);
        } catch (error) {
            throw new Error(`删除标签失败: ${error.message}`);
        }
    }
}
module.exports = TagService;